package offer.zixing.chapter05;

import java.util.HashMap;
import java.util.Map;

/**
 * 有效的变位词
 *
 * 给定两个字符串s和t，请判断它们是不是一组变位词。在一组变位词中，如果它们中的字符以及每个字符出现的次数都相同，
 * 但字符的顺序不能。例如"anagram"和"nagaram"就是一组变位词。
 */
public class Test032 {
    public static void main(String[] args) {
//        System.out.println(isAnagram1("anagram", "nagaram"));
//        System.out.println(isAnagram1("anagram", "nagarama"));
//        System.out.println(isAnagram2("anagram", "nagaram"));
//        System.out.println(isAnagram2("anagram", "nagarama"));
        System.out.println(isAnagram2("a", "a"));
    }

    public static boolean isAnagram1(String str1, String str2) {
        if (str1.length() != str2.length()) {
            return false;
        }

        int[] counts = new int[26];
        for (char ch : str1.toCharArray()) {
            counts[ch - 'a']++;
        }
        for (char ch : str2.toCharArray()) {
            if (counts[ch - 'a'] == 0) {
                return false;
            }
            counts[ch - 'a']--;
        }
        return true;
    }

    public static boolean isAnagram2(String str1, String str2) {
        if (str1.length() != str2.length()) {
            return false;
        }

        Map<Character, Integer> counts = new HashMap<>();
        for (char ch : str1.toCharArray()) {
            counts.put(ch, counts.getOrDefault(ch, 0) + 1);
        }
        for (char ch : str2.toCharArray()) {
            if (counts.getOrDefault(ch, 0) == 0) {
                return false;
            }
            counts.put(ch, counts.get(ch) - 1);
        }
        return true;
    }
}
